package com.itic.mall.system.marketuser.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.common.service.OutCommonService;
import com.itic.appbase.framework.common.constants.Constants;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.HttpRequestUtils;
import com.itic.appbase.framework.utils.IdGen;
import com.itic.appbase.framework.utils.NumberStringHelper;
import com.itic.appbase.framework.utils.RandomStringHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.UserSessionHelper;
import com.itic.mall.system.marketuser.persistence.model.MarketUser;
import com.itic.mall.system.marketuser.persistence.model.MarketUserExample;
import com.itic.mall.system.marketuser.persistence.model.MarketUserExample.Criteria;
import com.itic.mall.system.marketuser.service.MarketUserService;
import com.itic.mall.system.profitmoney.persistence.model.ProfitMoney;

import net.sf.json.JSONObject;


@Controller
@RequestMapping(value="/system/marketuser")
public class MarketUserController
     extends BaseController {
    @Autowired
    private MarketUserService marketUserService;

    @Autowired
	protected OutCommonService outCommonService;
    
    //////////////////////////////////////////////////////常量区////////////////////////////////////////////////////////////////
    private static final String MODEL_NAME_CHINA = "商家用户";//中文名
    private static final String MODEL_NAME＿ENGLISH = "marketuser";//英文名
    private static final String PAGE_COMMON_PATH = "/mall/system/marketuser/marketuser";//通用路径
    private static final String COMMON_URL = "/system/marketuser/";//通用路径
    

    //////////////////////////////////////////////////////页面跳转区////////////////////////////////////////////////////////////
   
    /*
     * 主页面
     */
    @RequestMapping(value="/init")
    public String init(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Main";
    }
    
    /*
     * 添加页面
     */
    @RequestMapping(value="/initAdd")
    public String initAdd(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Add";
    }
    
    /*
     * 编辑页面
     */
    @RequestMapping(value="/initEdit")
    public String initEdit(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		MarketUser temp = marketUserService.get(id);
    		model.addAttribute("editData",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	return PAGE_COMMON_PATH+"Edit";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initView")
    public String initView(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		
    		MarketUser temp  = marketUserService.get(id);
    		
    		model.addAttribute("viewEdit",iticJsonMapper.toJson(temp));
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"View";
    }
    
    /*
     * 导入页面
     */
    @RequestMapping(value="/initImp")
    public String initImp(Model model){
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Imp";
    }
    
    /*
     * 查看页面
     */
    @RequestMapping(value="/initBind")
    public String initBind(String id , Model model){
    	if( StringHelper.isNotBlank(id) ) {
    		model.addAttribute("id",id);
    		model.addAttribute("name_china", MODEL_NAME_CHINA);
        	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
        	model.addAttribute("common_url", COMMON_URL);
    	}else {
            throw new ParameterErrorException();
        }
    	
    	return PAGE_COMMON_PATH+"Bind";
    }
    
    
    /*
     * 导入页面
     */
    @RequestMapping(value="/initGroup")
    public String initGroup(Model model,String id){
    	MarketUserExample example = new MarketUserExample();
        example.setOrderByClause("CREATE_TIME DESC");
        Criteria criteria = example.createCriteria();
        criteria.andInvitingIdEqualTo(id);
        // 获取信息总条数
        int total = marketUserService.count(example);
     
        // 获取数据
        List<MarketUser> list = marketUserService.list(example);
        MarketUser marketUser = marketUserService.get(id);
        String inviteId = marketUser.getInvitingId();
        MarketUser inviteUser = marketUserService.get(inviteId);
        model.addAttribute("invite", iticJsonMapper.toJson(inviteUser));
        model.addAttribute("data", iticJsonMapper.toJson(list));
        model.addAttribute("totalCount", total);
    	model.addAttribute("name_china", MODEL_NAME_CHINA);
    	model.addAttribute("name_english", MODEL_NAME＿ENGLISH);
    	model.addAttribute("common_url", COMMON_URL);
    	return PAGE_COMMON_PATH+"Group";
    }
    
    
    //////////////////////////////////////////////////////业务代码区////////////////////////////////////////////////////////////
    
    /**
     * 添加模板管理数据
     * @param android
     * @return
     */
    @RequestMapping(value="/add")
    @ResponseBody
    public Map<String,String> add(MarketUser MarketUser){
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         String url = "http://www.jhjvip.cn:8081/market/mobile/login/reg?unionId="+IdGen.uuid()+"&userNickName="+MarketUser.getUserNickName()+"&invitingCode=171127";
         String httpGet = HttpRequestUtils.httpGet(url);
         JSONObject fromObject = JSONObject.fromObject(httpGet);
 		 String resultHttp = fromObject.getString("result");
 		 if( "success".equals(resultHttp) ){
 			result = "success";
 			resultMap.put(IticConst.DATA, fromObject.getString("data"));
 		 }
 		 resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    public String getRandomInvitingCode(){
		 String code = RandomStringHelper.randomNumStr(6);
		 //查找下数据库中有没有人使用过
		 MarketUser user = marketUserService.getUserByInvitingCode(code);
		 if( null == user ){
			 return code;
		 }else{
			 return getRandomInvitingCode();
		 }
	}
    
    /**
     * <p>Title:queryCondition </p>
     * <p>Description:封装查询条件 </p>
     * @param jzdw
     * @param jzdwExample
     * @return
     */
    private MarketUserExample queryCondition(HttpServletRequest request,MarketUser temp,String isTGW,String isNull) {
    	
    	// 参数处理
        MarketUserExample example = new MarketUserExample();
       
        // 按排列号顺序
        example.setOrderByClause("CREATE_TIME DESC");

       // example.setOrderByClause("reorder asc");
        
        Criteria criteria = example.createCriteria().andIsEffectiveEqualTo( DBConst.TRUE );
      
        //过滤组织机构
        //User user = findUserSession(request);
        //criteria.andOrgCodeEqualTo(user.getOrganizationCode());
        if(StringHelper.isNotBlank(isTGW)){
        	    List<String> ids = marketUserService.getBindedTgwUserIds();	
        	    if("0".equals(isTGW)){
                	if(ids.size()>0){
                		criteria.andIdNotIn(ids);
                	}
            	}else{
                	if(ids.size()>0){
                		criteria.andIdIn(ids);
                	}
            	}
        }
        
        if( StringHelper.isNotBlank(isNull) ){
        	if( "have".equals(isNull) ){
        		criteria.andUserPhoneIsNotNull();
        	}else{
        		criteria.andUserPhoneIsNull();
        	}
        	
        }
        // 查询条件
        if ( null != temp ) {
    	    //模糊查询
            if ( StringHelper.isNotBlank( temp.getUserNickName() ) ) {
                criteria.andUserNickNameLike("%" + temp.getUserNickName() + "%");
            }
            
            //
            if( StringHelper.isNotBlank( temp.getUserPhone()) ){
            	criteria.andUserPhoneLike("%" + temp.getUserPhone() + "%");
            }
            
            if( StringHelper.isNotBlank( temp.getInvitingCode()) ){
            	criteria.andInvitingCodeLike("%" + temp.getInvitingCode() + "%");
            }
            
            if( StringHelper.isNotBlank( temp.getId()) ){
            	criteria.andIdLike("%" + temp.getId() + "%");
            }
        }
        return example;
    }
    
    /**
     * 
     * @param goldType
     * @param request
     * @return
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(MarketUser MarketUser, String isTGW,String isNull,HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        
        MarketUserExample example = this.queryCondition(request,MarketUser,isTGW,isNull);
        // 封装分页参数
        example = this.handlePageQuery(request, example);
        
        
        // 获取信息总条数
        int total = marketUserService.count(example);
        
        // 获取数据
        List<MarketUser> list = marketUserService.list(example);
        
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, total);
        resultMap.put(IticConst.DISPLAY_RECORDS, total);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        resultMap.put(IticConst.DATA, list);
        return resultMap;

    }
    
    /**
     * 编辑保存
     * @param MarketUser
     * @return
     */
    @RequestMapping(value="/edit")
    @ResponseBody
    public Map<String,String> edit(String delFileIds , MarketUser temp){
    
    	if( StringHelper.isNotBlank(delFileIds) ){
    		// 删除附件
    		outCommonService.deleteFiles(delFileIds);
    	}
    	
    	 Map<String, String> resultMap = new HashMap<String, String>();
         String result = ResponseCode.SERVER_ERROR.getCode();
         result = marketUserService.edit(temp);
         
         resultMap.put(IticConst.RESULT, result);
         return resultMap;
    }
    
    

    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/del")
    @ResponseBody
    public Map<String, String> del(String ids) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        if (StringHelper.isNotBlank(ids)) {
        	
            List<String> idList = Arrays.asList(ids.split(","));
            
            MarketUserExample example = new MarketUserExample();
            example.createCriteria().andIdIn(idList);
          
            MarketUser temp = new MarketUser();
            result = marketUserService.deleteByExample(temp, example);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/bind")
    @ResponseBody
    public Map<String, String> bind(String id,String code) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        //批量删除
        if (StringHelper.isNotBlank(id) && StringHelper.isNotBlank(code) ) {
        	 MarketUser user1 = marketUserService.get(id);
        	 MarketUser user2 = marketUserService.getByInvitingCode(code);
        	 
        	 if( null != user1 && null != user2 ){
        		 
        		 String invitingId = user1.getInvitingId();
        		 MarketUser marketUser = marketUserService.get(invitingId);
        		 
        		 //设置原来的人数相减
        		 String subPeople = NumberStringHelper.subtractString(marketUser.getSuccessPeople(), "1");
        		 marketUser.setSuccessPeople(subPeople);
        		 
        		 //设置用户的邀请人ID
            	 user1.setInvitingId(user2.getId());
            	 
            	 //给邀请人添加相应的人数
            	 String user2SuccessPeople = user2.getSuccessPeople();
            	 if( StringHelper.isBlank(user2SuccessPeople) ){
            		 user2SuccessPeople = "0";
            	 }
            	 String addString = NumberStringHelper.addString(user2SuccessPeople, "1");
            	 user2.setSuccessPeople(addString);
            	 
            	 result = marketUserService.bind(marketUser,user1,user2);
        	 }else{
        		 result = ResponseCode.PARAM_INVALID.getCode();
        	 }
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }

        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
    /**
     * 删除
     * 
     */
    @RequestMapping(value = "/changeMoney")
    @ResponseBody
    public Map<String, String> changeMoney( String id, String money,String note ) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.SERVER_ERROR.getCode();

        if( StringHelper.isNoneBlank(id) && StringHelper.isNoneBlank(money) && StringHelper.isNoneBlank(note) ){
        	//更新用户金额
        	MarketUser user = marketUserService.get(id);
        	if( null != user ){
        		String userMoney = user.getMoney();
        		if( StringHelper.isBlank(userMoney) ){
        			userMoney = "0";
        		}
            	userMoney = NumberStringHelper.addString(userMoney, money);
            	user.setMoney(userMoney);
            	
                String userTotalProfit = user.getTotalProfit();
                if( StringHelper.isBlank(userTotalProfit) ){
                	userTotalProfit = "0";
        		}
                userTotalProfit = NumberStringHelper.addString(userTotalProfit, money);
                user.setTotalProfit(userTotalProfit);
                
            	//添加一条收入明细，异常记录备注
            	ProfitMoney profitMoney = new ProfitMoney();
            	profitMoney.setId(IdGen.uuid());
            	profitMoney.setCreateTime(new Date());
            	profitMoney.setUpdateTime(new Date());
            	profitMoney.setIsEffective(DBConst.TRUE);
            	profitMoney.setCreateUser(null != UserSessionHelper.get(Constants.USER_ID) ? UserSessionHelper
                         .get(Constants.USER_ID) : "unknown");
            	profitMoney.setOrgCode(null != UserSessionHelper.get(Constants.USER_ORG) ? UserSessionHelper
                         .get(Constants.USER_ORG) : "unknown");
               
            	profitMoney.setUserId("系统管理员");
            	profitMoney.setOrderId("无");
            	profitMoney.setOrderNum("999999999");
            	profitMoney.setOrderTotalMoney(money);
            	profitMoney.setMarketUserId(user.getId());
            	profitMoney.setUserNickName(user.getUserNickName());
            	
            	profitMoney.setMoney(money);
            	profitMoney.setNote(note);
            	profitMoney.setType("001");
            	
            	result = marketUserService.editMoney(user,profitMoney);
            	
        	}
        	
        }
        
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }
    
}